package com.example.smartwaterapi.controller;

import com.example.smartwaterapi.common.api.RestApiResponse;
import com.example.smartwaterapi.entity.Device;
import com.example.smartwaterapi.service.DeviceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 设备控制器
 */
@Tag(name = "设备管理API", description = "智能水杯设备相关接口")
@RestController
@RequestMapping("/api/device")
public class DeviceController {

    private static final Logger log = LoggerFactory.getLogger(DeviceController.class);
    
    @Autowired
    private DeviceService deviceService;
    
    /**
     * 获取设备信息
     */
    @Operation(summary = "获取设备详情", description = "根据设备ID获取设备详细信息")
    @GetMapping("/{id}")
    public RestApiResponse<Device> getDeviceInfo(@Parameter(description = "设备ID") @PathVariable Long id) {
        Device device = deviceService.getById(id);
        if (device == null) {
            return RestApiResponse.notFound("设备不存在");
        }
        return RestApiResponse.ok(device);
    }
    
    /**
     * 根据设备序列号获取设备
     */
    @Operation(summary = "根据序列号获取设备", description = "根据设备序列号获取设备详细信息")
    @GetMapping("/sn/{deviceSn}")
    public RestApiResponse<Device> getDeviceBySn(@Parameter(description = "设备序列号") @PathVariable String deviceSn) {
        Device device = deviceService.getByDeviceSn(deviceSn);
        if (device == null) {
            return RestApiResponse.notFound("设备不存在");
        }
        return RestApiResponse.ok(device);
    }

    /**
     * 获取用户的设备列表
     */
    @Operation(summary = "获取用户设备列表", description = "获取指定用户绑定的所有设备列表")
    @GetMapping("/user/{userId}")
    public RestApiResponse<List<Device>> getUserDevices(@Parameter(description = "用户ID") @PathVariable Long userId) {
        log.debug("收到获取用户设备列表请求，用户ID: {}", userId);
        List<Device> devices = deviceService.getByUserId(userId);
        log.debug("查询到用户设备数量: {}", devices.size());
        if (!devices.isEmpty()) {
            log.debug("设备列表: {}", devices);
        } else {
            log.warn("⚠️ 用户 {} 没有绑定的设备，可能原因：1) 设备未绑定 2) 设备被删除 3) 用户ID不匹配", userId);
            // 额外检查：查询所有设备看是否存在该用户的设备
            log.debug("🔍 调试：查询数据库中所有设备数量进行对比");
        }
        return RestApiResponse.ok(devices);
    }

    /**
     * 绑定设备
     */
    @Operation(summary = "绑定设备", description = "将设备绑定到指定用户账号")
    @PostMapping("/bind")
    public RestApiResponse<Boolean> bindDevice(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "设备序列号") @RequestParam String deviceSn,
            @Parameter(description = "蓝牙设备ID") @RequestParam String deviceId,
            @Parameter(description = "MAC地址") @RequestParam String macAddress,
            @Parameter(description = "设备名称") @RequestParam String deviceName,
            @Parameter(description = "设备型号") @RequestParam(required = false, defaultValue = "SWB-2024") String model,
            @Parameter(description = "电池电量") @RequestParam(required = false, defaultValue = "100") Integer batteryLevel,
            @Parameter(description = "当前水量(ml)") @RequestParam(required = false, defaultValue = "0") Integer currentVolume,
            @Parameter(description = "水温") @RequestParam(required = false) Double waterTemperature,
            @Parameter(description = "设备时区") @RequestParam(required = false, defaultValue = "Asia/Shanghai") String deviceTimezone,
            @Parameter(description = "设备认证令牌") @RequestParam(required = false) String deviceToken,
            @Parameter(description = "EDR地址") @RequestParam(required = false) String edrAddress,
            @Parameter(description = "BLE地址") @RequestParam(required = false) String bleAddress) {
        boolean success = deviceService.bindDevice(userId, deviceSn, deviceId, macAddress, deviceName, model, 
                batteryLevel, currentVolume, waterTemperature, deviceTimezone, deviceToken, edrAddress, bleAddress);
        if (success) {
            return RestApiResponse.ok(true);
        }
        return RestApiResponse.badRequest("绑定设备失败，设备可能已被其他用户绑定或MAC地址冲突");
    }

    /**
     * 解绑设备（仅解除绑定关系，保留设备记录）
     */
    @Operation(summary = "解绑设备", description = "解除设备与用户账号的绑定关系，保留设备记录")
    @PostMapping("/unbind")
    public RestApiResponse<Boolean> unbindDevice(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "设备序列号") @RequestParam String deviceSn) {
        boolean success = deviceService.unbindDevice(userId, deviceSn);
        if (success) {
            return RestApiResponse.ok(true);
        }
        return RestApiResponse.badRequest("解绑设备失败");
    }

    /**
     * 删除设备
     */
    @Operation(summary = "删除设备", description = "删除用户绑定的设备，完全移除设备记录")
    @PostMapping("/delete")
    public RestApiResponse<Boolean> deleteDevice(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "设备序列号") @RequestParam String deviceSn) {
        boolean success = deviceService.deleteUserDevice(userId, deviceSn);
        if (success) {
            return RestApiResponse.ok(true);
        }
        return RestApiResponse.badRequest("删除设备失败");
    }

    /**
     * 更新设备在线状态
     */
    @Operation(summary = "更新设备在线状态", description = "更新设备的在线/离线状态")
    @PutMapping("/online-status")
    public RestApiResponse<Boolean> updateOnlineStatus(
            @Parameter(description = "设备序列号") @RequestParam String deviceSn,
            @Parameter(description = "是否在线") @RequestParam Boolean isOnline) {
        boolean success = deviceService.updateOnlineStatus(deviceSn, isOnline);
        if (success) {
            return RestApiResponse.ok(true);
        }
        return RestApiResponse.badRequest("更新设备在线状态失败");
    }

    /**
     * 更新设备电量
     */
    @Operation(summary = "更新设备电量", description = "更新设备当前电量百分比（0-100）")
    @PutMapping("/battery")
    public RestApiResponse<Boolean> updateBatteryLevel(
            @Parameter(description = "设备序列号") @RequestParam String deviceSn,
            @Parameter(description = "电量百分比(0-100)") @RequestParam Integer batteryLevel) {
        if (batteryLevel < 0 || batteryLevel > 100) {
            return RestApiResponse.badRequest("电量必须在0-100之间");
        }
        boolean success = deviceService.updateBatteryLevel(deviceSn, batteryLevel);
        if (success) {
            return RestApiResponse.ok(true);
        }
        return RestApiResponse.badRequest("更新设备电量失败");
    }

    /**
     * 更新设备水量和水温
     */
    @Operation(summary = "更新设备水量和水温", description = "更新设备当前水量（毫升）和水温（摄氏度）")
    @PutMapping("/water-status")
    public RestApiResponse<Boolean> updateWaterStatus(
            @Parameter(description = "设备序列号") @RequestParam String deviceSn,
            @Parameter(description = "当前水量(ml)") @RequestParam Integer currentVolume,
            @Parameter(description = "水温(℃)") @RequestParam(required = false) Double waterTemperature) {
        boolean success = deviceService.updateWaterStatus(deviceSn, currentVolume, waterTemperature);
        if (success) {
            return RestApiResponse.ok(true);
        }
        return RestApiResponse.badRequest("更新设备水量和水温失败");
    }
    
    /**
     * 更新设备设置
     */
    @Operation(summary = "更新设备设置", description = "更新设备的个性化配置信息")
    @PutMapping("/{id}/settings")
    public RestApiResponse<Boolean> updateDeviceSettings(
            @Parameter(description = "设备ID") @PathVariable Long id,
            @Parameter(description = "设备设置参数") @RequestBody Map<String, Object> settings) {
        boolean success = deviceService.updateDeviceSettings(id, settings);
        if (success) {
            return RestApiResponse.ok(true);
        }
        return RestApiResponse.badRequest("更新设备设置失败");
    }
    
    /**
     * 更新设备表盘背景URL
     */
    @Operation(summary = "更新设备表盘背景", description = "更新设备的表盘背景图片URL")
    @PutMapping("/dial-background")
    public RestApiResponse<Boolean> updateDialBackground(
            @Parameter(description = "设备序列号") @RequestParam String deviceSn,
            @Parameter(description = "表盘背景图片URL") @RequestParam String dialBackgroundUrl) {
        boolean success = deviceService.updateDialBackgroundUrl(deviceSn, dialBackgroundUrl);
        if (success) {
            return RestApiResponse.ok(true);
        }
        return RestApiResponse.badRequest("更新设备表盘背景失败");
    }
}
